package org.moonlight.jvm.natives.sun.misc.vm;

import org.moonlight.jvm.instructions.base.MethodInvokeLogic;
import org.moonlight.jvm.natives.AbstractNativeMethod;
import org.moonlight.jvm.rtda.exclusive.Frame;
import org.moonlight.jvm.rtda.share.Object;
import org.moonlight.jvm.rtda.share.heap.Class;
import org.moonlight.jvm.rtda.share.heap.ClassLoader;
import org.moonlight.jvm.rtda.share.heap.classmember.Method;
import org.moonlight.jvm.rtda.share.methodarea.StringPool;

/**
 *  sun.misc.VM  private static native void initialize();
 *
 *  自动拆箱装箱:
 *    Integer.valueOf()方法并不是每次都创建Integer()对象，而是维护了一个缓存池IntegerCache。对于比较小（默认是-128～127）的int变量，
 *    在IntegerCache初始化时就预先加载到了池中，需要用时直接从池里取即可。IntegerCache是Integer类的内部类
 *    IntegerCache在初始化时需要确定缓存池中Integer对象的上限值，为此它调用了sun.misc.VM类的getSavedProperty()方法。
 *
 * @author Moonlight
 * @createTime 2023/11/9 16:04
 **/
public class Initialize extends AbstractNativeMethod {

    public Initialize() {
        super("sun/misc/VM", "initialize", "()V");
    }

    @Override
    public void nativeMethod(Frame frame) {
        Class clazz = frame.getMethod().getClazz();

        Object savedProps = clazz.getRefVar("savedProps", "Ljava/util/Properties;");
        frame.getOperandStack().pushRef(savedProps);

        Object key = StringPool.myString(clazz.getLoader(), "Key");
        frame.getOperandStack().pushRef(key);

        Object val = StringPool.myString(clazz.getLoader(), "Val");
        frame.getOperandStack().pushRef(val);

        Class properties = clazz.getLoader().loadClass("java/util/Properties");
        Method setProperty = properties.getInstanceMethod(
                "setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;"
        );

        MethodInvokeLogic.invokeMethod(frame, setProperty);
    }
}
